import { getSize } from '../../utils/dom-utils';
import _ from 'lodash';

function Handwriting(el) {
  this.el = el;
  this.canvas = this._createCanvas();
  this.ctx = this.canvas.getContext('2d');
  this.ctx.fillStyle = 'rgba(255,0,0,1)';
  var _this = this;
  this.canvas.onmousedown = function(e) {
    _this.downEvent(e);
  };
  this.canvas.onmousemove = function(e) {
    _this.moveEvent(e);
  };
  this.canvas.onmouseup = function(e) {
    _this.upEvent(e);
  };
  this.canvas.onmouseout = function(e) {
    _this.upEvent(e);
  };
  this.moveFlag = false;
  this.upof = {};
  this.radius = 0;
  this.has = [];
  this.lineMax = 30;
  this.lineMin = 3;
  this.linePressure = 1;
  this.smoothness = 80;
}

Handwriting.prototype._createCanvas = function() {
  const canvas = document.createElement('canvas');
  const size = getSize(this.el);
  canvas.width = size.width;
  canvas.height = size.height;
  this.el.appendChild(canvas);
  return canvas;
};

Handwriting.prototype.clear = function() {
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
};

Handwriting.prototype.downEvent = function(e) {
  this.moveFlag = true;
  this.has = [];
  this.upof = this.getXY(e);
};

Handwriting.prototype.moveEvent = function(e) {
  if (!this.moveFlag) {
    return;
  }
  var of = this.getXY(e);
  var up = this.upof;
  var ur = this.radius;
  this.has.unshift({ time: new Date().getTime(), dis: this.distance(up, of) });
  var dis = 0;
  var time = 0;
  for (var n = 0; n < this.has.length - 1; n++) {
    dis += this.has[n].dis;
    time += this.has[n].time - this.has[n + 1].time;
    if (dis > this.smoothness) {
      break;
    }
  }
  var or =
    Math.min(time / dis * this.linePressure + this.lineMin, this.lineMax) / 2;
  this.radius = or;
  this.upof = of;
  // if (this.has.length <= 4) { return; }
  var len = Math.round(this.has[0].dis / 2) + 1;
  for (var i = 0; i < len; i++) {
    var x = up.x + (of.x - up.x) / len * i;
    var y = up.y + (of.y - up.y) / len * i;
    var r = ur + (or - ur) / len * i;
    this.ctx.beginPath();
    this.ctx.arc(x, y, r, 0, 2 * Math.PI, true);
    this.ctx.fill();
  }
};

Handwriting.prototype.upEvent = function(e) {
  this.moveFlag = false;
};

Handwriting.prototype.getXY = function(e) {
  return {
    x: e.offsetX,
    y: e.offsetY
  };
};

Handwriting.prototype.distance = function(a, b) {
  const x = b.x - a.x,
    y = b.y - a.y;
  return Math.sqrt(x * x + y * y);
};

Handwriting.prototype.distance = function(a, b) {
  const x = b.x - a.x,
    y = b.y - a.y;
  return Math.sqrt(x * x + y * y);
};

/**
 * 获取图片数据
 */
Handwriting.prototype.getImageData = function() {
  return this.ctx.getImageData(0, 0, this.el.clientWidth, this.el.clientHeight);
};
/**
 * 获取图片数据Url
 */
Handwriting.prototype.getImageDataUrl = function() {
  const imageData = this.getImageData();
  if (_.some(imageData.data, d => d)) {
    return this.ctx.canvas.toDataURL(imageData);
  }
  return null;
};

export default Handwriting;
